﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProjectManagement.Domain.Abstract;
using ProjectManagement.Domain.Entities;
using ProjectManagement.Domain.AutoMappings;
using NHibernate;
using NHibernate.Linq;

namespace ProjectManagement.Domain.Services
{
	public class RoleService:IRepository<Role>
	{
		private ISessionFactory factory = NHibernateHelper.CreateSessionFactory();
		public void Save(Role entity)
		{
			var session = factory.OpenSession();
			using(ITransaction trans=session.BeginTransaction())
			{
				session.Save(entity);
				trans.Commit();
			}
		}

		public void Remove(Role entity)
		{
			var session = factory.OpenSession();
			using (ITransaction trans = session.BeginTransaction())
			{
				session.Delete(entity);
				trans.Commit();
			}
		}

		public void SaveOrUpdate(Role entity)
		{
			var session = factory.OpenSession();
			using (ITransaction trans = session.BeginTransaction())
			{
				session.SaveOrUpdate(entity);
				trans.Commit();
			}
		}

		public void Update(Role entity)
		{
			var session = factory.OpenSession();
			using (ITransaction trans = session.BeginTransaction())
			{
				session.Update(entity);
				trans.Commit();
			}
		}

		public IEnumerable<Role> QueryAll()
		{
			using (var session = factory.OpenSession())
			{
				return session.Query<Role>()
					.ToList();
			}
		}

		public Role GetRoleById(int id)
		{
			using(var session=factory.OpenSession())
			{
				return session.Get<Role>(id); 
			}
		}

		public Role Get(int id)
		{
			using (var session = factory.OpenSession())
			{
				return session.Get<Role>(id);
			}
		}

		public IEnumerable<Role> QueryRole(IEnumerable<Role> source, string roleName, string description)
		{
			return source
				.WhereIf(r => r.Name.Contains(roleName), string.IsNullOrEmpty(roleName) == false)
				.WhereIf(r => r.Description.Contains(description), string.IsNullOrEmpty(description) == false)
				.ToList();
		}
	}
}
